<template>
  <Modal v-model:visible="visible" title="编辑企业应用授权" @cancel="close" :destroy-on-close="true">
    <template #footer>
      <Button key="submit" type="primary" @click="submit">确认</Button>
      <Button key="back" @click="close">取消</Button>
    </template>
    <Descriptions :column="1">
      <DescriptionsItem label="企业">{{ tenantName }}</DescriptionsItem>
      <DescriptionsItem label="应用">{{ appName }}</DescriptionsItem>
      <DescriptionsItem label="套餐">{{ packageType }}</DescriptionsItem>
    </Descriptions>
    <Form :model="formState" v-bind="formItemLayout" ref="formRef">
      <FormItem label="到期时间" name="expireTime" :rules="[{ required: true, message: '请选择到期时间' }]">
        <DatePicker
          v-model:value="formState.expireTime"
          :disabled-date="disabledDate"
          :showToday="false"
          placeholder="请选择"
          :defaultPickerValue="dayjs(originExpireTime)"
        />
      </FormItem>
    </Form>
  </Modal>
</template>
<script lang="ts" setup>
import { Modal, Form, FormItem, DatePicker, message, Button, Descriptions, DescriptionsItem } from 'ant-design-vue';
import dayjs, { Dayjs } from 'dayjs';
import { ref } from 'vue';
import { editAppAuth } from '/@/api/tenant-mgmt/enterpriseAppAuth/enterpriseAppAuth';
import { EditAppAuthParams } from '/@/api/tenant-mgmt/enterpriseAppAuth/model/enterpriseAppAuthModel';

const visible = ref(false);
const tenantName = ref();
const appName = ref();
const packageType = ref();
const formState = ref({} as EditAppAuthParams);
const originExpireTime = ref();
const disabledDate = (current: Dayjs) => {
  return current < dayjs(originExpireTime.value).endOf('day') || current > dayjs('9999-12-31 23:59:59');
};

const openEdit = (record) => {
  tenantName.value = record.tenantName;
  appName.value = record.appName;
  packageType.value = record.packageType;
  formState.value.id = record.id;
  if (record.expireTime !== '--') {
    originExpireTime.value = record.expireTime;
    formState.value.expireTime = dayjs(record.expireTime).endOf('date');
  } else {
    originExpireTime.value = dayjs();
    formState.value.expireTime = undefined;
  }
  visible.value = true;
};

const formRef = ref();
const emit = defineEmits(['submitSuccess']);
const close = () => {
  visible.value = false;
  formState.value = {} as EditAppAuthParams;
  formRef.value.clearValidate();
};

const submit = () => {
  let param = {} as EditAppAuthParams;
  formRef.value.validate().then(async () => {
    let expireTime = dayjs(formState.value.expireTime).endOf('date').format('YYYY-MM-DD HH:mm:ss');
    param = { id: formState.value.id, expireTime };

    let res = await editAppAuth(param);
    if (res) {
      message.success(res);
    }
    emit('submitSuccess');
    close();
  });
};

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 14 },
};
defineExpose({ openEdit });
</script>
